import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axios from "../../utils/axios";
import { message } from "antd";
// import { useDispatch } from "react-redux";
import { setCredentials } from "../../features/authSlice.ts";
import PuzzleVerify from "../../components/PuzzleVerify/PuzzleVerify";
import "./login.css";

const LoginPage: React.FC = () => {
//   const dispatch = useDispatch();
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  //    const [loading, setLoading] = useState(false);
  const [retryCount, setRetryCount] = useState(0);
  const [isVerified, setIsVerified] = useState(false);
  const navigate = useNavigate();
  const handleLogin = async () => {
    if (!isVerified) {
      message.error("请先完成拼图验证");
      return;
    }

    // setLoading(true);
    try {
      const response = await axios.post("login", {
        account,
        password,
      });
      // dispatch(
      //   setCredentials({
      //     user: response.data.role,
      //     token: response.data.token,
      //   })
      // );

      const { username, role, userId, token } = response.data;
      localStorage.setItem("username", username);
      localStorage.setItem("userRole", role.toString());
      localStorage.setItem("userId", userId.toString());
      // localStorage.setItem('userRole', '2'); // 切换角色
      localStorage.setItem("token", token);

      if (role === 1) {
        navigate("/");
      } else {
        navigate("/box/cart");
      }
    } catch (error) {
      console.error("登录失败:", error);
      alert("登录失败，请检查用户名和密码");
      setRetryCount((c) => c + 1);
    }
  };

  useEffect(() => {
    const createSnowflake = () => {
      const snowflake = document.createElement("div");
      snowflake.classList.add("snowflake");
      snowflake.style.left = `${Math.random() * 100}vw`;
      snowflake.style.animationDuration = `${Math.random() * 3 + 2}s`;
      snowflake.style.animationDelay = `${Math.random() * 3}s`;
      document.body.appendChild(snowflake);

      setTimeout(() => {
        snowflake.remove();
      }, 5000);
    };

    const intervalId = setInterval(createSnowflake, 200);

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return (
    <div className="login-container">
      <div className="login-form">
        <h2>登录</h2>
        <label htmlFor="username">用户名:</label>
        <input
          type="text"
          placeholder="用户名"
          value={account}
          onChange={(e) => setAccount(e.target.value)}
        />
        <label htmlFor="password">密码:</label>
        <input
          type="password"
          placeholder="密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <div className="verify-area">
          <PuzzleVerify
            key={retryCount}
            onVerify={(success) => {
              console.log(success);
              setIsVerified(!success);
              if (!success && retryCount > 0) {
                message.error("验证失败，请重新拖动拼图");
              }
            }}
          />
        </div>
        <button onClick={handleLogin} disabled={!isVerified}
         style={{backgroundColor: isVerified ? 'green' : 'red'}}  // 可视化验证状态
        >
          登录
        </button>
      </div>
    </div>
  );
};

export default LoginPage;
// src/pages/Login.jsx
// import { useState, useEffect } from 'react';
// import { Form, Input, Button, message } from 'antd';
// import { LockOutlined, UserOutlined } from '@ant-design/icons';
// import { useDispatch } from 'react-redux';
// import { useNavigate, useLocation } from 'react-router-dom';
// import http from '../../utils/axios.ts';
// import { setCredentials } from '../../features/authSlice.ts';
// import PuzzleVerify from '../../components/PuzzleVerify/PuzzleVerify.tsx';
// import './Login.css';
// const Login = () => {
//   const [form] = Form.useForm();
//   const dispatch = useDispatch();
//   const navigate = useNavigate();
//   const location = useLocation();
//   const [loading, setLoading] = useState(false);
//   const [isVerified, setIsVerified] = useState(false);
//   const [retryCount, setRetryCount] = useState(0);

//   // 处理登录成功后的跳转
//   const from = location.state?.from?.pathname || '/';

//   useEffect(() => {
//     const searchParams = new URLSearchParams(location.search);
//     if (searchParams.get('expired')) {
//       message.warning('登录已过期，请重新登录');
//     }
//   }, [location]);

//   const handleLogin = async (values) => {
//     if (!isVerified) {
//       message.error('请先完成拼图验证');
//       return;
//     }

//     setLoading(true);
//     try {
//       const res = await http.post('/login', {
//         account: values.account,
//         password: values.password
//       });

//       dispatch(setCredentials({
//         user: res.data.role,
//         token: res.data.token
//       }));
      
//       message.success('登录成功');
//       localStorage.setItem('token', res.data.token);
//       localStorage.setItem('user', res.data.role);
//       navigate(from, { replace: true });
//     } catch (error) {
//       const errMsg = error.response?.data?.message || '登录失败';
//       message.error(errMsg);
//       setRetryCount(c => c + 1);
//     } finally {
//       setLoading(false);
//     }
//   };

//   return (
//     <div className="login-container">
//       <div className="login-box">
//         <div className="login-header">
//           <h2>数字人管理系统</h2>
//           <p>请使用账号密码登录</p>
//         </div>

//         <Form form={form} onFinish={handleLogin}>
//           <Form.Item
//             name="account"
//             rules={[{ required: true, message: '请输入用户名!' }]}
//             validateTrigger="onBlur"
//           >
//             <Input
//               prefix={<UserOutlined className="input-icon" />}
//               placeholder="用户名"
//               size="large"
//               autoComplete="username"
//               allowClear
//             />
//           </Form.Item>

//           <Form.Item
//             name="password"
//             rules={[{ required: true, message: '请输入密码!' }]}
//             validateTrigger="onBlur"
//           >
//             <Input.Password
//               prefix={<LockOutlined className="input-icon" />}
//               placeholder="密码"
//               size="large"
//               autoComplete="current-password"
//               allowClear
//             />
//           </Form.Item>

//           <div className="verify-area">
//             <PuzzleVerify 
//               key={retryCount}
//               onVerify={(success) => {
//                 console.log(success)
//                 setIsVerified(!success);
//                 if (!success && retryCount > 0) {
//                   message.error('验证失败，请重新拖动拼图');
//                 }
//               }}
//             />
//           </div>

//           <Button
//             type="primary"
//             htmlType="submit"
//             size="large"
//             block
//             loading={loading}
//             className="login-btn"
//             disabled={!isVerified}
//           >
//             {loading ? '登录中...' : '立即登录'}
//           </Button>
//         </Form>
//       </div>
//     </div>
//   );
// };

// export default Login;